<template>

  <div class="app-container" >

    <div class="filter-container">
        <el-col :sm='12' :lg='6' :xl='5'>
            <el-card class="box-card">

            <div slot="header" class="clearfix">
                <span>图库分类</span>

                <el-button
                @click="append(1,imagescategorydata)"
                style="float: right; padding: 3px 0"
                type="text"
                >新增分类</el-button>

                <el-button
                title="拖拽可进行排序"
                @click="categorysortsave()"
                style="float: right; padding: 3px 0;margin-right: 10px;"
                type="text"
                >保存排序</el-button>
            </div>

            <div style="margin-bottom: 20px;">
              <span
              @click="clickCategoryName({id: 0})"
              style="cursor: pointer;font-size: 14px;margin-left: 10px;">
              查看全部
              </span>

              <el-tag
              v-if="source"
              @click="freeimages()"
              style="cursor: pointer;font-size: 14px;margin-left: 10px;">
              免费图库
              </el-tag>
            </div>


            <el-tree
            ref="tree"
            :data="imagescategorydata"
            node-key="id"
            :props="defaultProps"
            :default-expand-all="false"
            :expand-on-click-node="false"
            :render-content="renderContent"
            draggable
            :allow-drop="allowDrop"
            @node-drag-end="handleDragEnd"
            >
            </el-tree>

            </el-card>

        </el-col>

        <el-col :sm='12' :lg='18' :xl='19'>

            <el-card>

            <div style="padding: 0 20px;">
                      <el-alert
                        title=""
                        type="error"
                        :closable="true">
                        <template slot>
                          温馨提示：请不要上传和使用非法/侵权/涉黄等图片！
                        </template>
                      </el-alert>

                      <div style="margin-top: 15px;">

                          <el-form ref="searchForm" :model="imagedata.listQuery" label-width="120px" :inline="true">

                            <el-form-item label="图片名称" prop="keyword">
                              <el-input placeholder="请输入图片名称" v-model="imagedata.listQuery.keywords" class="input-with-select" clearable/>
                            </el-form-item>

                            <el-form-item label="图片宽度" prop="width">
                              <el-input placeholder="图片宽度" v-model="imagedata.listQuery.width" class="input-with-select" style="width: 120px;" clearable/>
                            </el-form-item>

                            <el-form-item label="图片高度" prop="height">
                             <el-input placeholder="图片高度" v-model="imagedata.listQuery.height" class="input-with-select" style="width: 120px;" clearable/>
                            </el-form-item>

                            <el-form-item label="图片后缀" prop="suffix">
                              <el-select v-model="imagedata.listQuery.suffix" placeholder="图片后缀" clearable style="width: 120px" class="input-with-select" >
                                <el-option label="jpg" value="jpg" />
                                <el-option label="jpeg" value="jpeg" />
                                <el-option label="png" value="png" />
                                <el-option label="gif" value="gif" />
                              </el-select>
                            </el-form-item>

                            <el-form-item label="" prop="suffix">
                                <el-button size="mini" icon="el-icon-search" type="primary" @click="getImagesList"> 搜索</el-button>
                            </el-form-item>

                          </el-form>


                        <div>
                        <el-tooltip class="item" effect="dark" content="请点击左侧对应分类，进行上传！" placement="bottom">
                        <el-button
                        type="info"
                        @click="$alert('请点击左侧对应的图库分类，然后进行上传！', '上传说明')"
                        v-if="imagedata.current_category_id == 0"
                        >
                        <i class="el-icon-upload"></i>上传图片
                        </el-button>
                        </el-tooltip>
                        <el-upload
                          v-if="imagedata.current_category_id > 0"
                          style="width: 150px;display: inline-block;"
                          class="upload-demo"
                          :action="baseapi+'/admin/uploadpicture'"
                          :headers="headers"
                          :http-request="my_upload"
                          :data={cid:imagedata.current_category_id}
                          name="picture"
                          :multiple="true"
                          :before-upload="handleBeforeUpload"
                          :on-success="pictureSuccess"
                          :on-error="pictureError"
                          :show-file-list="false"
                          :limit="20"
                          accept=".png, .PNG, .jpg, .JPG, .JPEG, .jpeg, .GIF, .gif"
                          >
                          <el-button size="" type="primary" style="margin-right: 10px;">
                          <i class="el-icon-upload"></i>上传图片
                          </el-button>
                        </el-upload>

                        <el-tooltip class="item" effect="dark" content="请点击左侧对应分类，进行上传！" placement="bottom">
                        <el-button
                        type="info"
                        @click="$alert('请点击左侧对应的图库分类，然后进行上传！', '上传说明')"
                        v-if="imagedata.current_category_id == 0"
                        ><i class="el-icon-upload"></i>提取网络图片</el-button>
                        </el-tooltip>
                        <el-button
                        type="success"
                        @click="downloadpic(1)"
                        v-if="imagedata.current_category_id > 0"
                        ><i class="el-icon-upload"></i>提取网络图片</el-button>

                        <!-- 这里是裁剪图片的  裁剪图片的宽度和高度 这里放裁剪图片的方法-->
                        <!-- v-on:cutDown="cutDown" -->
                        <ImgCutter
                        :lockScroll="false"
                        :toolBoxOverflow="false"
                        rate='1:1'
                        toolBgc="#000"
                        :scaleAble="false"
                        WatermarkText=""
                        WatermarkTextFont="12px Sans-serif"
                        WatermarkTextColor="#00ff00"
                        :WatermarkTextX="0.95"
                        :WatermarkTextY="0.95"
                        @cutDown="cutDown"
                        >
                            <template #open>
                                <el-button>上传图片（可编辑）</el-button>
                            </template>
                        </ImgCutter>
                        </div>

                        <div style="margin-top: 20px;height: 40px;">

                        <el-select v-model="handledata.type" placeholder="操作" v-if="source == null" clearable>
                          <el-option label="移动 选择" value="1">
                          </el-option>

                          <el-option label="移动 分类" value="2">
                          </el-option>
                        </el-select>

                        <el-button
                        type="warning"
                        @click="move(1)"
                        v-if="handledata.type == 1 || handledata.type == 2">
                        移动
                        </el-button>

                        <!--全选-->
                        <el-checkbox
                        v-if="handledata.type == 1"
                        style="margin: 0 10px;"
                        :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                        全选
                        </el-checkbox>

                        <el-tag
                        type="danger"
                        v-if="imagedata.chose_picture.length > 0">
                        已选择 {{imagedata.chose_picture.length}} 张
                        </el-tag>
                        </div>

                      </div>

                      <div style="margin-top: 20px;">
                          <el-breadcrumb separator-class="el-icon-arrow-right">
                            <el-breadcrumb-item>图库</el-breadcrumb-item>
                            <el-breadcrumb-item>{{imagedata.current_category}}</el-breadcrumb-item>
                          </el-breadcrumb>
                      </div>

                      <el-row>
                        <el-checkbox-group v-model="imagedata.chose_picture">
                        <el-col :sm='12' :lg='6' :xl='4' v-for="(item, index) in imagedata.list"  style="padding:20px;">
                          <el-card
                          :body-style="{ padding: '10px'}"
                          shadow="always"
                          class="demo-image__preview"
                          :class="imagedata.chose_picture.includes(item) || imagedata.chose_picture.includes(item.id) ? 'checked' : ''"
                          >

                            <div style="width: 100px;margin: auto;">
                            <el-image
                            fit="scale-down"
                            :src="item.picture" class="image" @click="introHandle(index)"  style="width: 100px; height: 100px"
                            :preview-src-list="[item.picture]">
                            </el-image>
                            <div style="margin-top: 5px;"><el-tag size="mini">{{item.picture_width}} *{{item.picture_height}}</el-tag></div>
                            <div style="margin-top: 5px;">
                            <el-tag size="mini" type="danger">{{jisuansize(item.picture_size)}}</el-tag>
                            </div>
                            <div style="padding: 10px 2px 0px;overflow: hidden;height: 50px;">
                              <span
                              @click="updateChangeName(index)"
                              style="font-size: 12px;" :title="item.name" v-if="item.change_name == 0">
                              {{item.name}}
                              <i class="el-icon-edit" title="修改名称"></i>
                              </span>
                              <el-input v-model="item.name" v-if="item.change_name == 1"
                              @blur="saveImageName(index,item.id,item.name,'blur')"
                              @change="saveImageName(index,item.id,item.name,'change')">
                              </el-input>
                            </div>
                            </div>

                            <!-- 这是操作图片-->
                            <el-checkbox v-if="source == null && handledata.type == 1"
                            @change="handleCheckedChange"
                            :label="item.id"
                            style="margin: 10px 0 0;width: 100%;">
                            选这张
                            </el-checkbox>

                            <!-- 这是上传图片-->
                            <el-checkbox v-if="source == 'goodsadd'" :label="item"  style="margin: 10px 0 0;width: 100%;">
                            选择这张
                            </el-checkbox>
                          </el-card>
                        </el-col>
                        </el-checkbox-group>
                      </el-row>

                      <pagination v-show="imagedata.total>0" :total="imagedata.total" :page.sync="imagedata.listQuery.page" :limit.sync="imagedata.listQuery.limit" @pagination="getImagesList" />

                  </div>


            </el-card>

        </el-col>

    </div>


    <el-dialog title="图库分类编辑" :visible.sync="createFormBox">
      <el-form ref="form" :model="data" label-width="120px" :rules="rules" style="margin-top: 20px;">
            <el-form-item label="名称" prop="name">
                <el-input v-model="data.name"></el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input v-model="data.remark"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="categoryedit()">
                保存
                </el-button>
            </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="移动图片" :visible.sync="createFormBoxMove">
      <el-form ref="form-move" :model="handledata" label-width="120px" style="margin-top: 20px;">

            <el-form-item label="移动" prop="cid" v-if="handledata.type == 2">
                <el-cascader
                ref="move"
                :options="imagescategorydata"
                :props="{ checkStrictly: true,children: 'sons',label: 'name2', id: 'id'}"
                clearable></el-cascader>
            </el-form-item>

            <el-form-item label="移动到" prop="to_cid">
                <el-cascader
                ref="tomove"
                :options="imagescategorydata"
                :props="{ checkStrictly: true,children: 'sons',label: 'name2', id: 'id'}"
                clearable></el-cascader>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="move(2)">
                移动
                </el-button>
            </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="下载网络图片" :visible.sync="createFormBoxNetworkPic">
      <el-form ref="form-download" :model="downloadData" label-width="120px" style="margin-top: 20px;">

            <el-form-item label="网络图片地址" prop="networkpic">
                <el-input type="textarea" autosize v-model="downloadData.networkpic" @change="networkpicChange" placeholder="一行一个"></el-input>

                <el-image v-for="(item,index) in downloadData.networkpicarr" v-if="item"
                style="width: 100px; height: 100px"
                :src="item"
                :preview-src-list="[item]">
                </el-image>
                <el-alert
                type="info"
                title="请不要下载非法/侵权/涉黄等图片,否则后果自负！">
                </el-alert>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="downloadpic(2)">
                下载
                </el-button>
            </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>
<style>
/*.el-image__error, .el-image__placeholder, .el-image__inner {height:  auto;}*/
.checked{border: 1px solid #1890ff;}
</style>
<script>
import request from '@/utils/request'
import ImgCutter from 'vue-img-cutter'
import {imagescategorylist,imagescategorysortsave,imagescategoryadd,imagescategoryedit,imagescategorydel,imageslist,imagesmove,downloadnetworkpic,imagenamesave,uploadpicture} from '@/api/imagesgallery'
import { MessageBox, Message } from 'element-ui'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import draggable from 'vuedraggable'

export function uploadExcel(query,data) {
  return request({
      url: process.env.VUE_APP_BASE_API+'/admin/uploadpicture',
      method: 'post',
      headers: {'Authorization': getToken()},
      params: query,
      data
  })
}

export default {
  name: 'images-list',
  components: { Pagination, draggable,ImgCutter},
  props:['source','parameter'],
  directives: { waves },
  filters: {
  },
  data() {
    return {
      baseapi: process.env.VUE_APP_BASE_API,
      headers: {'Authorization': getToken()},
      defaultProps: {
        children: 'sons',
        label: 'name',
        id: 'id'
      },
      imagescategorydata:[],//图库分类列表数据
      /*imagescategorydata: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }],*/
      tableKey: 0,
      //图库分类数据
      data: {
        id: 0,
        title:"",
        remark: "",
        auth_ids: [],
      },
      //操作的图片
      handledata: {
          type: "",//操作方式
          cid: 0,
          ids: [],//要操作的图片id
          all_ids: [],//分页全部的图片id
      },
      isIndeterminate: true,
      checkAll: false,
      //要下载的网络图片
      downloadData: {
        networkpic: "",
        networkpicarr: [],
      },
      createFormBox: false,//创建表单盒子显示和隐藏
      createFormBoxMove: false,
      createFormBoxNetworkPic: false,//网络图片下载
      rules: {
        name: [{ required: true, message: '分类名称不能为空', trigger: 'change' }],
      },
      source: "",//来源
      imagedata: {
          imagesType: "",//cover banner
          chose_picture:[],//选中的所有图片
          current_category: "全部",//选中的图库分类名称
          current_category_id: 0,//选中的图库分类id（上传的时候默认就往这里面传）
          list: null,
          total: 0,
          listLoading: true,
          listQuery: {
            page: 1,
            limit: 30,
            cid: "0",//图库分类
            is_free: 0,//1的时候就是免费图库
            keywords: "",//搜索关键字
            width: "",
            height:"",
            suffix: "",
            sort: 'id_desc'//默认的排序
          },
        },
    }
  },
  watch:{
      source(value){
        this.source = value;
      },
      parameter(value) {

      },
  },
  created() {
    this.getImagesCategoryList()
    this.getImagesList();
  },
  methods: {
        //剪切上传
        cutDown(object){
          const formData = new FormData();
          let file=object.file
          formData.append('picture', file);
          formData.append("cid", this.imagedata.current_category_id);
          uploadpicture(formData).then(response => {
                  let code = response.code;
                  let msg = response.msg;

                  if (code == 200) {
                      this.getImagesList();
                      this.$message.success(msg);
                  } else {
                      MessageBox.confirm(msg, {
                        type: 'error',
                        showCancelButton: false,
                        showConfirmButton: false,
                      })
                  }

                }).catch(() => {
                });

        },
        //点击编辑图片，显示输入库
        updateChangeName(index) {
             this.imagedata.list[index]['change_name'] = 1;
        },
        //修改图片名称
        saveImageName(index,id,name,handle="blur"){
            if (handle == "blur") {
                this.imagedata.list[index]['change_name'] = 0;
            } else {
                imagenamesave({id: id,name: name}).then(response => {
                  let code = response.code;
                  let msg = response.msg;

                  if (code == 200) {
                      this.imagedata.list[index]['change_name'] = 0;
                      this.$message.success(msg);
                  } else {
                      MessageBox.confirm(msg, {
                        type: 'error',
                        showCancelButton: false,
                        showConfirmButton: false,
                      })
                  }

                }).catch(() => {
                });
            }
        },
        handleCheckAllChange(val) {
          this.imagedata.chose_picture =  val ? this.handledata.all_ids : [];
          this.isIndeterminate = false;
        },
        handleCheckedChange(value) {
          let checkedCount = value.length;
          this.checkAll = checkedCount === this.handledata.ids.length;
          this.isIndeterminate = checkedCount > 0 && checkedCount < this.handledata.ids.length;
        },
        //下载网络图片
        downloadpic(type){
          if (type == 1) {
              this.createFormBoxNetworkPic = true;
          } else {//正式下载
             var cid = this.imagedata.current_category_id;//要上传的分类id
             var networkpic = this.downloadData.networkpic;//要上传的网络图片地址

             if (!networkpic) {
               this.$message.error("请填写网络图片地址");
               return false;
             }

            const loading = this.$loading({
              lock: true,
              text: '正在下载……',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });

             downloadnetworkpic({cid: cid,networkpic: networkpic}).then(response => {
                loading.close();
                let code = response.code;
                let msg = response.msg;

                if (code == 200) {
                    this.$message.success(msg);
                } else {
                    MessageBox.confirm(msg, {
                      type: 'error',
                      showCancelButton: false,
                      showConfirmButton: false,
                    })
                }

                this.getImagesList();
                this.getImagesCategoryList();
            }).catch(() => {
              loading.close();
            });
          }
        },
        networkpicChange(){
          var networkpic = this.downloadData.networkpic;
          var networkpicarr = networkpic.split("\n");
          this.downloadData.networkpicarr = networkpicarr;
        },
        //计算size
        jisuansize(value){
            var size = parseFloat(value/1024).toFixed(2);

            if (size > 1024) {
              return size/1024+"M";
            } else {
              return size+"kb";
            }
        },
        //获得图库列表数据
        getImagesList() {
          const loading = this.$loading({
            lock: true,
            text: '正在查询中……',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          imageslist(this.imagedata.listQuery).then(response => {
            setTimeout(() => {
              loading.close();
            }, 100)

            let code = response.code;
            let msg = response.msg;

            if  (code == 200) {
              var list = response.response.data;
              var total = response.response.total;
              this.imagedata.list = list;
              this.imagedata.total = total;

              //设置全部图片id
              var all_ids = [];
              list.forEach(function (item, index) {
                 all_ids.push(item.id);
              });
              this.handledata.all_ids = all_ids;
            } else {
              this.$message({
              message: msg,
              type: 'error'
              });
            }
          }).catch(() => {
             loading.close();
          });
        },
        //点击确认选择图片（弃用了）
        okImage(){
            this.$message.success("选择成功！");
        },
        //确认选择(页面嵌套的)
        choseImage(){
            var chose_picture = this.imagedata.chose_picture;//当前选中的图片的所有

            var len = chose_picture.length;
            if (len == 0) {
                this.$message.error('请选择图片！');
                return false;
            }

            //参数限制
            var parameter = this.parameter;
            if(parameter){
              var num = parameter['num'];//限制上传几张图片

              if (num == 1) {
                  if (len != 1) {
                    this.$message.error('只能选择1张！');
                    return false;
                  }
              }
              if(num<len){
                this.$message.error(`只能选择张${num}！`);
                return false;
              }
            }

            //console.log(chose_picture);
            return chose_picture;
        },
        //清空选中的图片
        clearImage(){
          this.imagedata.chose_picture = [];
        },
        my_upload(params) {
            let fd = new FormData();
            fd.append("picture", params.file);
            fd.append("cid", this.imagedata.current_category_id);
            // query是放在params中接收的参数，fd是放在了body中接收
            var query = {};

            const loading = this.$loading({
              lock: true,
              text: '正在上传……',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });

            uploadExcel(query, fd).then(response => {
                loading.close();
                var code = response.code;
                var msg = response.msg;
                if (code == 200) {
                    this.getImagesList()
                    this.$message.success(msg);
                } else {
                    MessageBox.confirm(msg, {
                      type: 'error',
                      showCancelButton: false,
                      showConfirmButton: false,
                    })
                }
            }).catch(() => {
              loading.close();
            });
        },
        //上传图片失败后
        pictureError(response, file, fileList){
            //console.log(response);
            this.$message.warning({
                message: '上传失败！'
            })
            return false
        },
        handleBeforeUpload(file) {
            const uploadTypes = ['jpg', 'png', 'gif', 'jpeg']
            const filetype = file.name.replace(/.+\./, '')

            if (uploadTypes.indexOf(filetype.toLowerCase()) === -1) {
              this.$message.warning({
                message: '请上传后缀名为jpg、png、gif、jpeg的图片'
              })
              return false
            }
            return true
        },
        //上传图片成功后（弃用了）
        pictureSuccess(response, file, fileList){
            var code = response.code;
            var msg = response.msg;
            if (code == 200) {
                this.getImagesList()
                this.$message.success(msg);
                /*MessageBox.confirm(msg, {
                  type: 'success',
                  showCancelButton: false,
                  showConfirmButton: false,
                })*/
            } else {
              MessageBox.confirm(msg, {
                  type: 'error',
                  showCancelButton: false,
                  showConfirmButton: false,
                })
            }
        },
        //点击图库分类名称
        clickCategoryName(data){
            var cid = data.id;
            this.imagedata.listQuery.cid = cid;

            if (cid == 0) {
               var  current_category = "全部";
            } else {
               var  current_category = data.name;
            }

            this.imagedata.current_category = current_category;
            this.imagedata.current_category_id = cid;
            this.imagedata.listQuery.is_free = 0;
            this.getImagesList();
        },
        //免费图库
        freeimages(){
            this.imagedata.current_category = "免费图库";
            this.imagedata.current_category_id = 0;
            this.imagedata.listQuery.is_free = 1;
            this.getImagesList();
        },
        renderContent(h, { node, data, store }) {

            let level = node.level;
            if (level < 2) {
                var add =
                <el-tooltip class="item" effect="dark" content="增加子项" placement="bottom">
                <el-button size="mini" type="text" on-click={ () => this.append(node, data) }><i class="el-icon-circle-plus-outline"></i>
                </el-button>
                </el-tooltip>
            } else {
                var add = '';
            }

            if (data.id == this.imagedata.current_category_id) {
               var menu = <span style="font-size: 14px;margin-right: 5px;color: #ff002d;font-weight: bold;" on-click={ () => this.clickCategoryName(data) }>{node.label} （{data.num}张）</span>;
            } else {
               var menu = <span style="font-size: 14px;margin-right: 5px;" on-click={ () => this.clickCategoryName(data) }>{node.label} （{data.num}张）</span>;
            }

            return (
              <span class="custom-tree-node">
                {menu}
                <span>
                  {add}
                  <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
                  <el-button size="mini" type="text" on-click={ () => this.edit(data) }><i class="el-icon-edit-outline"></i></el-button>
                  </el-tooltip>

                  <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
                  <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }><i class="el-icon-delete-solid"></i></el-button>
                  </el-tooltip>
                </span>
              </span>);
        },
        handleNodeClick(data) {
          //console.log(data);
        },
        //拖拽结束触发的方法
        handleDragEnd(draggingNode, dropNode, dropType, ev) {
            //console.log('tree drag end: ', dropNode && dropNode.label, dropType);
            //alert("ddd");
            //console.log(this.imagescategorydata);
            //this.categorysortsave();
        },
        categorysortsave(){
            //分类排序
            const loading = this.$loading({
              lock: true,
              text: '排序保存中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });

            imagescategorysortsave({data:this.imagescategorydata}).then(response => {
                  loading.close();
                  var code = response.code;
                  var msg = response.msg;
                  if (code == 200) {
                    this.$message({
                      message: msg,
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: msg,
                      type: 'error'
                    });
                  }
              }).catch(() => {
                loading.close();
              });
        },
        // 拖拽时判定目标节点能否被放置
        // 'prev'、'inner' 和 'next'，前、插入、后
        allowDrop(draggingNode, dropNode, type) {
          if (draggingNode.data.level === dropNode.data.level) {
            if (draggingNode.data.parentId === dropNode.data.parentId) {
              return type === "prev" || type === "next";
            } else {
              return false;
            }
          } else {
            //不同级进行处理
            return false;
          }
        },
        //获得所有的图库分类
        getImagesCategoryList(){
            imagescategorylist({type: 1}).then(response => {
                if (response.code == 200) {
                  var imagescategorydata = this.imagescategorydata;
                  var res = response.response;
                  res.forEach(item => {
                    const menu = {
                      name: item.name,
                      name2: item.name2,
                      remark: item.remark,
                      sons: item.sons,
                      id: item.id,
                      num: item.num,
                      pid: item.pid,
                      sort: item.sort,
                      value: item.value,
                    }

                    imagescategorydata.push(menu)
                  })
                }
            }).catch(err => {

            })
        },
        //图库分类增加
        append(node, data) {
            var pid = data.id;
            imagescategoryadd({pid:pid}).then(response => {
                  var code = response.code;
                  var msg = response.msg;
                  if (code == 200) {
                        if (node == 1) {
                            this.imagescategorydata = [];
                            this.getImagesCategoryList();
                        } else {
                            var id = response.response.id;
                            var name = response.response.name;
                            const newChild = { id: id, name: name, num: 0, sons: [] };
                            if (!data.sons) {
                            this.$set(data, 'sons', []);
                            }
                            data.sons.push(newChild);
                        }
                  } else {
                    this.$message({
                      message: msg,
                      type: 'error'
                    });
                  }
            })
        },
        //编辑当前的图库分类
        edit(data) {
          this.data = data;
          this.createFormBox = true;
        },
        //图库分类修改
        categoryedit(){
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    imagescategoryedit(this.data).then((res) => {
                      var code = res.code;
                      var msg = res.msg;
                      if (code == 200) {
                          this.$message.success(msg);
                      } else {
                          this.$message.error(msg);
                      }
                    })
                }
            })
        },
        //删除当前的图库分类
        remove(node, data) {
            this.$confirm('确定删除此图库分类吗？其下所有子分类也会被删除！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              imagescategorydel({id:data.id}).then(response => {
                  var code = response.code;
                  var msg = response.msg;
                  if (code == 200) {
                      const parent = node.parent;
                      const sons = parent.data.sons || parent.data;
                      const index = sons.findIndex(d => d.id === data.id);
                      sons.splice(index, 1);
                  } else {
                    this.$message({
                      message: msg,
                      type: 'error'
                    });
                  }
              })
            });
          },
          //移动图片到其他的分类
          move(type){
            if (type == 1) {
              this.createFormBoxMove = true;
            } else {
              var type = this.handledata.type;

              //移动到哪个分类下
              const checkedNode =  this.$refs["tomove"].getCheckedNodes();
              if (checkedNode.length == 0) {
                this.$message.error("请选择移动到的分类！");
                return false;
              }
              var to_cid = checkedNode[0].value;
              this.handledata.to_cid = to_cid;


              if (type == 1) {//选择后移动
                this.handledata.ids = this.imagedata.chose_picture;
              } else if (type == 2) {//移动分类
                const checkedNode2 =  this.$refs["move"].getCheckedNodes();
                if (checkedNode2.length == 0) {
                  this.$message.error("请选择要移动的分类！");
                  return false;
                }
                var cid = checkedNode2[0].value;

                if (cid == to_cid) {
                  this.$message.error("分类相同，无法移动！");
                  return false;
                }
                this.handledata.cid = cid;
              }

              imagesmove(this.handledata).then(response => {
                  var code = response.code;
                  var msg = response.msg;
                  if (code == 200) {
                    this.clearImage();
                    this.$message.success(msg);
                    this.getImagesList();
                    this.getImagesCategoryList()
                  } else {
                    this.$message({
                      message: msg,
                      type: 'error'
                    });
                  }
              })
            }
          }


  }
}
</script>

